package com.stormragetech.teamwork.spring.controller.web;

import com.stormragetech.common.exception.StormragetechException;
import com.stormragetech.teamwork.common.constant.Constants;
import com.stormragetech.teamwork.module.project.entity.ProjectStruc;
import com.stormragetech.teamwork.module.project.spring.service.ProjectStrucService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Log4j2
@Controller
@RequestMapping("/proj")
public class ProjectController {

    private final ProjectStrucService projectStrucService;

    @Autowired
    public ProjectController(ProjectStrucService projectStrucService) {
        Assert.notNull(projectStrucService, "ProjectStrucService cannot be null !!!");
        this.projectStrucService = projectStrucService;
    }


    @RequestMapping(value = "/struc/create", method = RequestMethod.GET)
    public String createStruc(String errMsg, Model model) {

        System.out.println();
        log.info("[ Controller ] ------ project -- struc -- config ------ [ GET ] ------ start ");

        if (null != errMsg && errMsg.length() > 0) {
            model.addAttribute(Constants.RETURN_MSG, errMsg);
        }
        return "proj/struc_c";

    }

    @RequestMapping(value = "/struc/create", method = RequestMethod.POST)
    public String createStruc(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) {

        System.out.println();
        log.info("[ Controller ] ------ project -- struc -- create ------ [ POST ] ------ start ");

        //TODO: decrypt password

        String[] name = request.getParameterValues("name");
        String[] type = request.getParameterValues("type");
        String version = request.getParameter("version");

        try {
            projectStrucService.create(name, type, version);
        } catch (StormragetechException e) {
            return "redirect:/proj/struc_c";
        }

        return "redirect:/index";

    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {

        System.out.println();
        log.info("[ Controller ] ------ project -- create ------ [ GET ] ------ start ");

        try {
            ProjectStruc struc = projectStrucService.findLastStruc();

            model.addAttribute("strucs", struc);
            return "proj/create";

        } catch (StormragetechException e) {
            return "proj/create";
        }
    }


}
